package com.aspire.nm.component.miniServerDemo.server;

import java.security.interfaces.RSAPrivateKey;

import com.aspire.nm.component.miniServer.Filter;
import com.aspire.nm.component.miniServer.annotation.filter.FilterRequest;
import com.aspire.nm.component.miniServer.annotation.filter.FilterResponse;
import com.aspire.nm.component.miniServer.protocol.Request;
import com.aspire.nm.component.miniServer.protocol.Response;
import com.aspire.nm.component.util.BytesUtil;
import com.aspire.nm.component.util.RSAEncrypt;
import com.aspire.nm.component.util.RsaKeyUtil;

public class RsaFilterImpl implements Filter {
	
    private static String privateKeyStr = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKGj/GVlfqqB2dYxyOM5v2vYrj0+"+
            "xpw5RJGTfOAh/L66wvwH4Ft2i6BUCbITK6FZsHrZ9weZNfySq28Z1eym63VitP+C7y9OwwjHr4ug"+
            "GBIWPln0EU//hmcmXx/oz0LeHBisHpVxjNYxl5Gkcf5nC1zZSVnx9YmNOjEEQqZyuL99AgMBAAEC"+
            "gYB2W5FQ3cSmLXbItKOYXoyf94V+Kx1a/0QKJKjnpXtgXXiw+0N5NZB/0YlX71mfSAFFs5yC39j8"+
            "HJmTPKO8KW122JKWkNhUv3X9EnMp0jLyQ2GTKD5Goa1Dn0T4gZtM3AKlDE0DfY1SVkqe45e+xSnw"+
            "zNJJVSiKrCWsZK1fubGjsQJBANWJDKT3AgHyx+KqJ/7VvgmLvT5c48nnQCkEhoFcR/FmisTKXwiO"+
            "rT8Wg6fgaLZT9YwgaqAqIkkR/tRNZ/HPewsCQQDByQGCJ7COKMNxNwAI+3XLgkmxUpy73SJbODPW"+
            "8djD3qAnYGtb6GqbweAN0U+LlVYm1yzHIDm50QvJWiyFIQSXAkA3Ti22NDuS4Zyfuk5tlFKKCmVT"+
            "V5+v1XMqrH9h1dLUVSiv23JNtxZr9prWyiqUvp4kUukK3p7OqhiESCAZ4xENAkBW6uRtT4YGTUxU"+
            "NHokjT0peZe6HDbGoInvZkcCKtmyCOHGp52fzKA8mnn3WKGYFvRcWXjxG4goyxXBS1vanpOjAkEA"+
            "udPWvKSKmbcuoBBUxylAvHoZiu1mY3WKbECxBE1WUMdcrPzl/fbEVUBXj/C8HYwi+kTUEzOy9FGV"+
            "+Gt9lTKl+w==";
            
    private static RSAPrivateKey privateKey;
    static{
        try {
            privateKey = RsaKeyUtil.string2privateKey(privateKeyStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
	
    
    
    
	@FilterRequest(pathPattern = "demo/rsa")
	public String decrypt(Request request) {
        //解密
        byte[] plainText;
        try {
            
            plainText = new RSAEncrypt().decrypt(privateKey, BytesUtil.hex2bytes(request.getPostdate()));
        } catch (Exception e) {
            return e.toString();
        }
        //数据变更为解密后的数据
        request.setPostdate(plainText);
        return null;
	}

	@FilterResponse(pathPattern = "demo/rsa")
	public String encrypt(Response response){
	    //加密
        byte[] cipher;
        try {
            cipher = new RSAEncrypt().encrypt(privateKey, response.getContentBytes());
        } catch (Exception e) {
            return e.toString();
        }
        //数据变更为加密后的数据
        response.setContentBytes(BytesUtil.bytes2hex(cipher).getBytes());
        return null;
	}
}
